<?php

include_once ('../utilities.php')

?>
<!DOCTYPE html>
<html>
<head>
	<link rel="stylesheet" type="text/css" href="../reset.css">
	<link rel="stylesheet" type="text/css" href="../mainStyle.css">
	<link rel="stylesheet" type="text/css" href="../searchButton.css">
	<title>SHPE</title>
</head>
<body>

	<div id="container">
		<?php

$root = '../';
include_once ('../header.php')

?>
        
		<div id="page-body">
            <?php

$editPermissions = false;
$deletePermissions = false;

if (!empty($_SESSION['LoggedIn']) && !empty($_SESSION['User']))
{
    // Determine the user's 'edit' and 'delete' permissions.
    $user = unserialize($_SESSION['User']);
    $permissions = $user->getPermissions();
    $query = "SELECT * FROM Permissions WHERE PermissionID = " . $permissions;
    $result = $mysqli->query($query);
    if ($result->num_rows > 0 && ($user->getChapter()->getChapterID() == $_GET["id"] ||
        $_GET["id"] == -1))
    {
        $row = $result->fetch_array(MYSQLI_ASSOC);
        switch ($row['Title'])
        {
            case "President":
            case "Vice-President":
            case "Web-Admin":
                $editPermissions = true;
                $deletePermissions = true;
                break;
        }
    }

    // Check if the event exists (ID > 0). If the ID is -1, a 'create new event page' needs to be shown instead.
    if ($_GET["id"] > 0)
    {

        // Get event data.
        $query = "SELECT * FROM Events WHERE EventID = " . $_GET["id"];
        $result = $mysqli->query($query);

        if ($result->num_rows < 1)
        {
            echo "The event requested does not exist.";
        }
        // Else, show the event.
        else
        {
            $eventRow = $result->fetch_array(MYSQLI_ASSOC);

            // If the users has 'edit' and 'delete' permissions, and the action leading to this page was not a
            // 'delete project submit', the user is either just viewing the project, or is editing the project.
            if (($editPermissions || $deletePermissions) && empty($_POST["delete"]) && empty
                ($_POST["save"]))
            {

?><form name="edit-event" action="./?id=<?=

                $_GET["id"]

?>" method="post"><?php

                // If the user was directed to this page from an 'edit event submit', load the page as 'editable' (a form with fields).
                if ($editPermissions)
                {
                    if (!empty($_POST["edit"]))
                    {
                        // Display form to edit event.


?>
	                                    <input type="submit" name="save" value="Save Event" class="editButton">
	                                    <input type="submit" name="cancel" value="Cancel" class="editButton">
	                                    <br /><br />
	                                    Name: <input type="text" name="name" value="<?=

                        $eventRow['Name']

?>">
	                                    <br />
										Date: <input type="date" name="date" value="<?=

                        date('Y-m-d', strtotime($eventRow['EventDate']))

?>">
										<br />
										Time: <input type="time" name="time" value="<?=

                        date('H:i', strtotime($eventRow['EventDate']))

?>">
										<br /><br />
	                                    Description:
	                                    <br />
	                                    <textarea type="text" name="description" style="width:600px; height:200px;"><?=

                        $eventRow['Description']

?></textarea>
	                                <?php

                    }
                    // Else just show the edit button at the top of the page (the 'viewable' version of the data will be loaded later).
                    else
                    {

?>
	                                    <input type="submit" name="edit" value="Edit Event" class="editButton">
	                                <?php

                    }
                }

                // If the user has 'delete' permissions, show the delete button if not in 'edit mode'.
                if ($deletePermissions)
                {
                    if (empty($_POST["edit"]) && empty($_POST["save"]))
                    {

?>
	                                    <input type="submit" name="delete" value="Delete Event" onclick="return confirm('Are you sure you want to delete this event?');" class="editButton">
	                                <?php

                    }
                }

?>
	                        </form>
	                        <br />
	                        <?php

            }

            // If sent to this page from a 'delete event' postback, delete the project.
            if (!empty($_POST["delete"]))
            {
                // Delete the event and go back to the chapter page.
                $query = "DELETE FROM Events WHERE EventID = " . $_GET["id"];
                $mysqli->query($query) or die('There was an error deleting the event.' . $mysqli->
                    error);
                echo "The event was deleted successfully!";
            }
            // Otherwise, if not in 'edit mode', check to see if the event was just edited and saved.
            else
                if (empty($_POST["edit"]))
                {
                    // Display event.
                    if (!empty($_POST["save"]))
                    {
                        // The event was just saved. If it's a new event, create it, otherwise update the existing one.
                        if (!empty($_GET["id"]))
                        {
                            // The event exists. Update it.
                            $formattedDate = $_POST["date"] . " " . $_POST["time"];
                            $formattedName = trim($_POST["name"]);
                            if ($formattedName == '')
                                $formattedName = "Untitled Event";
                            $query = sprintf("UPDATE Events SET Name='%s', EventDate='%s', Description='%s' WHERE EventID = %s",
                                $mysqli->real_escape_string($formattedName), $formattedDate, $mysqli->
                                real_escape_string($_POST["description"]), $_GET["id"]);

                            $mysqli->query($query) or die('There was an error updating the event.');

                            if (($editPermissions || $deletePermissions) && empty($_POST["delete"]))
                            {

?>
										<form name="edit-event" action="./?id=<?=

                                $_GET["id"]

?>" method="post">
											<input type="submit" name="edit" value="Edit Event" class="editButton">
											<?php

                                if ($deletePermissions)
                                {
                                    if (empty($_POST["edit"]))
                                    {

?>
														<input type="submit" name="delete" value="Delete Event" onclick="return confirm('Are you sure you want to delete this event?');" class="editButton">
													<?php

                                    }
                                }

?>
										</form>
										<br />
										<?php

                            }
                        }
                    }
                    // Get event data (it might have just been updated from a save above).
                    $query = "SELECT * FROM Events WHERE EventID = " . $_GET["id"];
                    $result = $mysqli->query($query);
                    $eventRow = $result->fetch_array(MYSQLI_ASSOC);

                    $formattedDescription = str_replace(array(
                        "\r\n",
                        "\n",
                        "\r"), '<br />', $eventRow['Description']);

?>
	                        <h1><?=

                    $eventRow['Name']

?></h1>
	                        <br />
	                        <h2><?=

                    date('g:i a \o\n m/d/Y', strtotime($eventRow['EventDate']))

?></h2>
	                        <br />
	                        <p><?=

                    $formattedDescription

?></p>
	                    <?php

                }
        }
    }
    // If this else reached, the event ID specified when loading the page is < 0, so a new event is being created.
    else
    {
        // New event being created.
        if (($editPermissions))
        {

?><form name="edit-event" action="./?id=-1" method="post"><?php

            // If 'create' request is empty, display a form to create an event.
            if (empty($_POST["create"]))
            {
                // Set a 'cancel' button that goes back to the chapter page that this 'create event' request was sent from.
                if (!empty($_SESSION['LastViewedChapterID']))
                {

?>
										<input type="submit" name="cancel" value="Cancel" onclick="document.forms['edit-event'].action='<?=

                    $root

?>chapter/?id=<?=

                    $_SESSION['LastViewedChapterID']

?>'" class="editButton">
									<?php

                }

                // Display form to edit event.


?>
                                    <input type="submit" name="create" value="Save Event" class="editButton">
                                    <br /><br />
                                    Name: <input type="text" name="name">
                                    <br />
                                    Date: <input type="date" name="date">
                                    <br />
                                    Time: <input type="time" name="time">
                                    <br /><br />
                                    Description:
                                    <br />
                                    <textarea type="text" name="description" style="width:600px; height:200px;"></textarea>
                                <?php

            }
            // Else, if there is a 'create' request, the form was filled out and this is a postback to submit the new event.
            else
            {
                // An event was created. Insert it into the database, get the new ID, and postback with that ID.
                $formattedDate = $_POST["date"] . " " . $_POST["time"];
                $formattedName = trim($_POST["name"]);
                if ($formattedName == '')
                    $formattedName = "Untitled Event";
                $query = sprintf("INSERT INTO Events (Name, EventDate, Description, ChapterID) VALUES ('%s', '%s', '%s', '%s')",
                    $mysqli->real_escape_string($formattedName), $formattedDate, $mysqli->
                    real_escape_string($_POST["description"]), $mysqli->real_escape_string($user->
                    getChapter()->getChapterId()));

                $mysqli->query($query) or die('There was an error creating the event.' . $mysqli->
                    error);
                echo "The event was created successfully!";
            }

?>
                        </form>
                        <?php

        }
    }
} else
{

?>
				<p>You must be logged in to view this page.</p>
				<?php

}

?>
		</div>
		
		<?php

include_once ('../footer.php')

?>
	</div>

</body>
</html>